package titan.data.components;

import java.io.File;

import titan.messages.Messages;
import titan.utils.FileUtils;

/**
 * Class to load a component engine
 */
public class ComponentEngine {
	private File itself;
	private File commit;
	private File prepare;
	private String name;

	/**
	 * @see ComponentEngine#setFile(File)
	 */
	public ComponentEngine(File file){
		 setFile(file);
	}

	/**
	 * Set commit, prepare and main engine files, based on file name:
	 * set to prepare when file ends with ".prepare.php";
	 * set to commit when file ends with ".commit.php";
	 * set to main engine file otherwise.
	 * @param file - the file to set
	 */
	public void setFile(File file){
		if(file.getName().endsWith(".prepare.php")) //$NON-NLS-1$
			prepare = file;
		else if(file.getName().endsWith(".commit.php")) //$NON-NLS-1$
			commit = file;
		else{
			itself = file;
			name = file.getName().substring(0, file.getName().lastIndexOf(".php")); //$NON-NLS-1$
		}
	}

	/**
	 * Get engine name
	 * @return engine name
	 */
	public String getName(){
		return name;
	}

	/**
	 * Copy the engine to the given path
	 * @param destination - the destination path
	 * @throws Exception if it doesn't get to copy some file
	 */
	public void copy(String destination) throws Exception{
		File dest;
		try {
			if(prepare != null){
				dest  = new File(destination+prepare.getName());
				FileUtils.copyFile(prepare, dest);
			}
			if(itself != null){
				dest  = new File(destination+itself.getName());
				FileUtils.copyFile(itself, dest);
			}
			if(commit != null){
				dest  = new File(destination+commit.getName());
				FileUtils.copyFile(commit, dest);
			}
		} catch (Exception e) {
			throw new Exception(Messages.ErCopyEngine+name+": "+e.getMessage()); //$NON-NLS-1$
		}
	}
}